package com.william.jdbcplus.core.toolkit;

import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;

import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;

/**
 * 注解公共方法
 */
public class ReflectionsUtil {

    /**
     * 获取类型的子类集合
     *
     * @param type        类型
     * @param skanPackage 扫描包路径
     * @param <T>
     * @return
     */
    public static <T> Set<Class<? extends T>> getSubClassSet(Class<T> type, String skanPackage) {
        // 设置扫描路径
        Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(skanPackage))
                .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));
        // 扫描包内带有@annotation注解的所有类集合 
        Set<Class<? extends T>> classSet = reflections.getSubTypesOf(type);
        Set<Class<? extends T>> result = new HashSet<Class<? extends T>>();
        for (Class<? extends T> clazz : classSet) {
            boolean isAbstract = Modifier.isAbstract(clazz.getModifiers());
            if (!isAbstract) {
                result.add(clazz);
            }
        }

        return result;
    }
}
